package com.wsd.smartcarwasher.controller;

import com.wsd.smartcarwasher.annotation.Log;
import com.wsd.smartcarwasher.constans.ResultState;
import com.wsd.smartcarwasher.dao.RedpacketMapper;
import com.wsd.smartcarwasher.domain.*;
import com.wsd.smartcarwasher.service.CouponService;
import com.wsd.smartcarwasher.service.RedPacketService;
import com.wsd.smartcarwasher.service.UserCouponService;
import com.wsd.smartcarwasher.service.WxService;
import com.wsd.smartcarwasher.util.DateUtil;
import com.wsd.smartcarwasher.util.ReturnUtil;
import com.wsd.smartcarwasher.util.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.*;

/**
 * 红包相关
 * Created by DaTangYun  YT on 2020/6/15 16:40
 */
@Api(tags = "(新增)红包相关")
@CrossOrigin
@Controller
public class RedPacketController {
    private static final Logger logger = LoggerFactory.getLogger(RedPacketController.class);
    @Resource
    private RedPacketService redPacketService;
    @Resource
    private CouponService couponService;
    @Resource
    private UserCouponService userCouponService;
    @Resource
    private WxService wxService;
    @Resource
    private RedpacketMapper redpacketMapper;
    /**
     * 新增红包（必须添加的是用户已生成的优惠券）
     * @param redpacket
     * @return
     */
    @Log("添加红包")
    @ApiOperation(value="新增红包", notes = "红包配置", produces = "application/json", response = ModelMap.class)
    @RequestMapping(value = "/v1/createPacket", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public ModelMap createActivity(@RequestBody Redpacket redpacket){
        if(redpacket.getpacketId()!=null)
        {
            this.redpacketMapper.deleteByPrimaryKey(redpacket.getpacketId());
        }

        redpacket.setCreatetime(new Date());
        redpacket.setCode(null);
        int ls =redPacketService.createPacket(redpacket);
        if(ls==0){
            return ReturnUtil.Error("红包添加失败");
        }

        return ReturnUtil.Success("红包添加成功");
    }
    @ApiOperation(value="红包生成二维码", notes = "生成二维码", produces = "application/json", response = ModelMap.class)
    @RequestMapping(value = "/v1/Packet/code", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    @ResponseBody
    public ModelMap createPacketCode(@RequestParam(value = "redpacketId") int redpacketId) throws IOException {

        //为该红包生成二维码
        return ReturnUtil.Success("红包添加成功",this.redPacketService.generateRedPacketWxCode(this.redPacketService.getPacket(redpacketId)));
    }
    @ApiOperation(value="红包查看", notes = "红包展示", produces = "application/json", response = ModelMap.class)

    @RequestMapping(value = "/v1/showPacket", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    @ResponseBody
    public ModelMap showPacket(@RequestParam Integer Page,@RequestParam Integer PageSize) {

        return ReturnUtil.Success(ResultState.QUERY_REDPACKET_SUCCESS.getMsg(), new Pagination<>(Page, PageSize, redPacketService.showPacket()));

    }
    @Log("编辑红包")
    @ApiOperation(value="红包更新", notes = "编辑红包", produces = "application/json", response = ModelMap.class)
    @RequestMapping(value = "/v1/updatePacket", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public ModelMap updatePacket(@RequestBody Redpacket redpacket) {
        if(redpacket.getpacketId()!=0||redpacket.getpacketId()!=null)
        {
            this.redpacketMapper.deleteByPrimaryKey(redpacket.getpacketId());
        }

        redpacket.setCreatetime(new Date());
        int ls =redPacketService.createPacket(redpacket);
        if(ls==0){
            return ReturnUtil.Error("修改失败");
        }
        return ReturnUtil.Success("修改成功");

    }
    @Log("删除了红包")
    @ApiOperation(value="红包删除", notes = "删除红包", produces = "application/json", response = ModelMap.class)
    @RequestMapping(value = "/v1/deletePacket", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    @ResponseBody
    public ModelMap deletePacket(@RequestParam int id) {

        int ls =redPacketService.deletePacket(id);
        if(ls==0){
            return ReturnUtil.Error("删除失败");
        }
        return ReturnUtil.Success("删除成功");

    }
    @Log("查看了红包")
    @ApiOperation(value="红包列表", notes = "红包列表", produces = "application/json", response = ModelMap.class)
    @RequestMapping(value = "/v1/listPacket", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    @ResponseBody
    public ModelMap listPacket(@RequestParam("Page") int Page, @RequestParam(value = "PageSize",defaultValue = "10") int PageSize, HttpServletRequest request) {
        RedpacketExample redpacketExample=new RedpacketExample();
        redpacketExample.createCriteria().andStatusEqualTo(true);
        List<Redpacket> ls=this.redpacketMapper.selectByExample(redpacketExample);
        return ReturnUtil.Success("操作成功",new Pagination(Page, PageSize,ls));

    }
    /**
     * 用户随机领取红包
     * @param request
     * @param packetId
     * @return
     */
    @Log("用户随机领取红包")
    @ApiOperation(value="根据红包中随机优惠卷id添加优惠券给用户", notes = "用户优惠券", produces = "application/json", response = ModelMap.class)
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "userId", value = "用户id", required = true, dataType = "String"),
//            @ApiImplicitParam(name = "packetId", value = "红包id", required = true, dataType = "Integer")
//    })
    @RequestMapping(value = "/v1/gainPacket", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    @ResponseBody
    public ModelMap gainPacket(HttpServletRequest request,
                               @RequestParam("packetId") int packetId) {
        //拿取用户id
        String sessionId = request.getHeader("authorization");
        UserInfo user = this.wxService.getUserInfoBySessionId(sessionId);
        if (user==null)
        {
            ReturnUtil.Error(ResultState.GET_USER_INFO_FAILED.getMsg());
        }
        //根据红包id查出红包，随机出红包的优惠券id
        Redpacket redpacket=redPacketService.getPacket(packetId);
        String [] arr=redpacket.getCouponid().split(",");
        List<String> list= Arrays.asList(arr);
        List<String> arrayList=new ArrayList<String>(list);
        //随机出优惠券id
        int couponId=new Random().nextInt(arrayList.size());
        //根据优惠券id查询出红包绑定的优惠券
        Coupon coupon = couponService.getCouponByCouponId(couponId);
        //2021.04.02  领取红包报错更改    更改人：yangtao
        if(StringUtil.isNullOrEmpty(coupon))
        {
            return ReturnUtil.Error(ResultState.COUPON_NOT_EXIST.getMsg());
        }

        while(coupon.getEndTime()!= null &&coupon.getEndTime().before(new Date())&&!arrayList.isEmpty())
        {
            //删除现有随机数组的随机数
            arrayList.remove(arrayList.remove(couponId));
            couponId=new Random().nextInt(arrayList.size());
            coupon = couponService.getCouponByCouponId(couponId);
        }
        if (arrayList.isEmpty()) {
            return ReturnUtil.Error("已经领完了");
        }
        UserCoupon userCoupon = userCouponService.getUserCouponByIdAndUserId(couponId,user.getUserId());
        if (userCoupon != null) {
            return ReturnUtil.Error("已经领取过了！");
        }
        if (coupon == null) {
            return ReturnUtil.Error(ResultState.COUPON_NOT_EXIST.getMsg());
        }
        if(coupon.getEndTime()!= null &&coupon.getEndTime().before(new Date())){
            return ReturnUtil.Error("优惠卷已经过期！");
        }
        userCoupon = userCouponService.getValidUserCouponByCouponId(couponId);
        if (userCoupon == null) {
            return ReturnUtil.Error("已经领完了");
        }
        Date addTime = DateUtil.getSysTime();
        userCoupon.setAddTime(addTime);
        if (coupon.getValidDate() < 0) {
            userCoupon.setEndTime(null);
        } else if(coupon.getValidDate()>0){
            userCoupon.setEndTime(DateUtil.getDateLater(addTime, coupon.getValidDate()));
        }else if(coupon.getStartTime()!=null && coupon.getEndTime()!=null){
            userCoupon.setEndTime(coupon.getEndTime());
            userCoupon.setStartTime(coupon.getStartTime());
        }
        userCoupon.setUserId(user.getUserId());
        int rows = userCouponService.bindUserCouponByCode(userCoupon);
        if (rows<0) {
            return ReturnUtil.Error(ResultState.ADD_COUPON_FAIL.getMsg());
        }
        return ReturnUtil.Success(ResultState.ADD_COUPON_SUCCESS.getMsg(),userCoupon);
    }
}
